package com.example.cjldemo.controller;


import com.example.cjldemo.entity.User;
import com.example.cjldemo.entity.vo.UserSaveVo;
import com.example.cjldemo.service.UserService;
import com.example.cjldemo.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mr.chi
 * @since 2023-10-31
 */

@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @ApiOperation(value = "根据用户ID获取用户信息")
    @GetMapping("/{id}")
    public String getUser(@PathVariable("id") Integer id){
        if(id == null || id <= 0){
            return "参数错误！";
        }
        User user = userService.getById(id);
        if(user == null){
            return "当前用户不存在，参数错误";
        }
        return user.toString();
    }



    @ApiOperation(value = "插入用户信息")
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertUser(@Validated @RequestBody UserSaveVo user){
        User saveUser = new User();
        //BeanUtil.copyProperties(user,saveUser);
        boolean flag = userService.save(saveUser);
        return AjaxResult.success(flag ? "新增成功" : "新增失败",flag);
    }

}

